<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" class="search-form">
      <el-form-item label="公告标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入公告标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发布状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
        >
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
    </el-row>

    <!-- 公告表格区域 -->
    <el-table v-loading="loading" :data="noticeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" prop="id" width="80" align="center" />
      <el-table-column label="标题" prop="title" min-width="150" />
      <el-table-column label="内容" prop="content" min-width="200">
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top">
            <div style="max-width: 300px">{{ scope.row.content }}</div>
            <div slot="reference">{{ scope.row.content | ellipsis }}</div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="发布人" prop="publisher" width="120" align="center" />
      <el-table-column label="发布时间" prop="createTime" width="160" align="center">
        <template slot-scope="scope">
          {{ parseTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status" width="100" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === '1' ? 'success' : 'info'">
            {{ scope.row.status === '1' ? '已发布' : '草稿' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
          <el-button
            v-if="scope.row.status !== '1'"
            size="mini"
            type="text"
            icon="el-icon-s-promotion"
            @click="handlePublish(scope.row)"
          >发布</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增/编辑对话框 -->
    <notice-form
      ref="noticeForm"
      @refresh="getList"
    />
  </div>
</template>

<script>
import { listNotice, delNotice, delNotices, publishNotice } from '@/api/notice'
import { parseTime } from '@/utils/ruoyi'
import Pagination from '@/components/Pagination'
import NoticeForm from './components/NoticeForm'

export default {
  name: 'NoticeIndex',
  components: {
    Pagination,
    NoticeForm
  },
  filters: {
    // 添加ellipsis过滤器
    ellipsis(value) {
      if (!value) return '';
      if (value.length > 100) {
        return value.slice(0, 100) + '...';
      }
      return value;
    }
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 公告表格数据
      noticeList: [],
      // 状态选项
      statusOptions: [
        { value: '0', label: '草稿' },
        { value: '1', label: '已发布' }
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: undefined,
        status: undefined,
        type: 'system'  // 只查询系统消息
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    parseTime,
    /** 查询公告列表 */
    getList() {
      this.loading = true
      listNotice({
        ...this.queryParams,
        type: 'system',  // 只查询系统消息
        userId: 1  // 添加管理员用户ID，确保能看到所有公告包括草稿
      }).then(response => {
        if (response && response.rows) {
          this.noticeList = response.rows.map(row => ({
            ...row,
            publisher: this.getSenderName(row)
          }))
          this.total = response.total
        } else {
          this.noticeList = []
          this.total = 0
        }
        this.loading = false
      }).catch(error => {
        console.error('获取公告列表失败:', error)
        this.$message.error('获取公告列表失败')
        this.loading = false
      })
    },
    /** 获取发布人名称 */
    getSenderName(row) {
      try {
        const extra = JSON.parse(row.extra || '{}')
        return extra.senderName || '管理员'
      } catch (e) {
        return '管理员'
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryForm.resetFields()
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$refs.noticeForm.show()
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const noticeId = row ? row.id : null;
      const selectedIds = this.ids;
      
      if (noticeId) {
        // 单个删除
        this.$confirm('是否确认删除该公告?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          return delNotice(noticeId);
        }).then(() => {
          this.getList();
          this.$message.success('删除成功');
        }).catch(() => {});
      } else if (selectedIds.length > 0) {
        // 批量删除
        this.$confirm('是否确认批量删除选中的公告?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          return delNotices(selectedIds.join(','));
        }).then(() => {
          this.getList();
          this.$message.success('批量删除成功');
        }).catch(() => {});
      }
    },
    /** 发布按钮操作 */
    handlePublish(row) {
      this.$confirm('是否确认发布该公告?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        return publishNotice(row.id)
      }).then(() => {
        this.$modal.msgSuccess('发布成功')
        this.getList()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
  ::v-deep .el-form-item {
    margin-bottom: 0;
  }
}
</style>
